Understanding the Difference Between scan and scanln in Go

Understanding the Difference Between scan and scanln in Go

Hi, this is Charu from Classmethod. I recently came across similar looking but different purpose keywords in GoLang: scan and scanln. These both are the methods used for user input. While they might seem similar at first glance, understanding their differences can prevent headaches and streamline your code. So, let's dive in.

Introduction to scan and scanln:

Both scan and scanln are methods used in Go for reading user input from the standard input (stdin). They are part of the fmt package, which provides functions for formatting and printing.

Scan:

This function reads input from the standard input and stores it into space-separated values. It stops scanning at the first whitespace character (space, newline, tab) and returns the number of items successfully scanned.

Scanln:

Similar to scan, scanln reads input from the standard input, but it stops scanning at a newline character. Unlike scan, it automatically appends a newline character to the input, making it suitable for reading lines of text.

Usage:

Scan:

Scan is ideal when you know the exact format of the input you're expecting. For instance, if you're reading integers separated by spaces or floats separated by commas, scan provides a clean way to parse such input.

var a, b int
fmt.Print("Enter two integers: ")
fmt.Scan(&a, &b)

Scanln:

Scanln, on the other hand, is more suited for reading lines of text. It automatically appends a newline character, making it convenient for scenarios where you expect the user to input text followed by a return key press.

var name string
fmt.Print("Enter your name: ")
fmt.Scanln(&name)

Conclusion:

Understanding the difference between scan and scanln in Go is crucial for efficient handling of user input. While scan is suited for formatted input, scanln is preferable for reading lines of text. By choosing the appropriate method based on your input requirements, you can write cleaner, more robust code.

Thank you for reading!

Happy Learning:)

Share this article

facebook logohatena logotwitter logo

© Classmethod, Inc. All rights reserved.